import requests  # pip install requests
import sseclient   # pip install sseclient-py


# def with_requests(url, headers):
#     """Get a streaming response for the given event feed using requests."""
#     return requests.get(url, stream=True, headers=headers)
#     # return requests.post(url, stream=True, headers=headers)

# 第一种方式
def sse_client(url, headers):
    """
    pip install sseclient-py
    """
    # response = requests.request('get', url, stream=True, headers=headers)
    # response = requests.get(url, stream=True, headers=headers)
    response = requests.request('post', url, stream=True, headers=headers)
    # response = requests.post(url, stream=True, headers=headers)
    
    # response = with_requests(url, headers)
    client = sseclient.SSEClient(response)
    for event in client.events():
        # print(event)
        print(event.data)


# 第二种方式
def sse_with_requests(url, headers):
    # response = requests.request('get', url, stream=True, headers=headers)
    # response = requests.get(url, stream=True, headers=headers)
    response = requests.request('post', url, stream=True, headers=headers)
    # response = requests.post(url, stream=True, headers=headers)
    
    # response = with_requests(url, headers)
    response.encoding = 'utf-8'
    for chunk in response.iter_content(chunk_size=None, decode_unicode=True):
        # 处理接收到的数据块
        print(chunk)


if __name__ == "__main__":
    url = "http://127.0.0.1:8080/sse2"
    headers = {"Accept": "text/event-stream"}
    # sse_client(url, headers)
    sse_with_requests(url, headers)